import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import {
  getUserFan,
  listUserFanWithUserStats,
  updateUserFan,
} from "../../service/userFanService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
import pageMW from "../../middleware/pager";
import Router from "koa-router";
const router = new Router();

router.get(
  "user-fans",
  "/usr/user/:userId/fans",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { userId } = ctx.params;
    let { keyword } = ctx.query;
    const { limit, offset, ts } = ctx;
    const { total, items } = await listUserFanWithUserStats(
      {
        userId,
        keyword,
      },
      {
        limit,
        offset,
        ts,
      }
    );

    const followerRecentNews = await listAggsToUserRecentNewses(
      items.map((it) => it.followerUserId)
    );
    const recentNewsMap = reduceToObject(
      followerRecentNews,
      (o) => o.userId,
      (o) => o.latestTime
    );
    ctx.body = {
      total,
      rows: items.map((it) => ({
        recentNews: recentNewsMap[it.followerUserId],
        ..._pick(
          it,
          "userFanId",
          "aliasName",
          "followerUserNickName",
          "followerUserPic",
          "involveActivityCount",
          "viewCount",
          "payAmount",
        ),
      })),
    };
  }
);

router.get("/usr/fans", (ctx: AppCTX) => {
  const { userId } = ctx;
  const url = router.url("user-fans", { userId }, { query: ctx.query });
  ctx.redirect(url);
  ctx.status = 301;
});

// 备注粉丝名称
router.put("/usr/fan/alias/:userFanId", async (ctx: AppCTX, next) => {
  const { userFanId } = ctx.params;
  const { aliasName } = ctx.request.body;
  const { userId } = ctx;
  //1 userId 必须是fan的user_id
  let userFan = await getUserFan(userFanId);
  if (userId !== userFan.userId) {
    ctx.throw(403, "no permit alias fan");
  }
  userFan = await updateUserFan({ userFanId, aliasName });
  ctx.body = {
    ..._pick(userFan, "userFanId", "aliasName"),
  };
});

export default router;
